package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.domian.Menu;
import com.itheima.domian.Role;
import com.itheima.domian.UserLogin;
import com.itheima.service.MenuService;
import com.itheima.service.UserLoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author althle
 * @create 08-25-15:12
 * @功能
 * @注释
 */

public class UserServicedo implements UserDetailsService {


    @Reference
    private UserLoginService userLoginService;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Reference
    private MenuService menuService;

    public static Map<String ,UserLogin> map = new HashMap<>();
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UserLogin byName = userLoginService.findByName(username);
        List<Role> roleList = userLoginService.findRoleList(byName.getId());
        byName.setRoleList(roleList);

        List<Menu> menuList = menuService.findAll();
        for (Menu menu : menuList) {
            String path = menu.getPath();
            List<Menu> menus = menuService.findMenuByParentId(path);
            menu.setChildren(menus);
        }
        for (Role role : roleList) {
            role.setMenuList(menuList);
        }


        if(byName == null){
         //根据用户名没有查询到用户
         return null;
        }

        String passwordInDb =  byName.getPassword();
        List<GrantedAuthority> list = new ArrayList<>();
        //授权，后期需要改为查询数据库动态获得用户拥有的权限和角色
        list.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

        UserDetails user = new User(username,passwordInDb,list);
        return user;
    }


}
